<template>
  <div class="actcone">
        <el-button class="cheaback" type="text" icon="el-icon-back" @click="hback"
      >返回</el-button
    >
    <el-tabs>
      <h5>商品信息</h5>
     
      <!-- 商品信息 -->
      <el-form ref="form" :model="form" label-width="80px" :rules="rulesss" label-position="right" @submit.native.prevent>
        <el-form-item class="actcc" label="商品名称">
          <el-input class="accionceg" v-model="form.title"></el-input>
        </el-form-item>
        <div class="vienger">
        <el-form-item class="accent" label="商品分类" >
       <div class="block">
         <span class="demonstration"></span>
        <el-select v-model="!form.categories[0] || !form.categories[0].id ? null : form.categories[0].id + '?' + form.categories[0].desc" placeholder="请选择" @change="handleChange">
    <el-option
      v-for="item in options"
      :key="item.id"
      :label="item.name"
      :value="item.id + '?' + item.name"
       >
    </el-option>
  </el-select>
       </div>
        </el-form-item>
        <el-form-item label="单位">
          <el-input class="xxloen" v-model="form.attributes[3].value"></el-input>
        </el-form-item>
           <el-form-item class="chpdea" label="商品产地">
          <el-input
          class="acton"
          v-model="form.attributes[1].value"
          ></el-input>
        </el-form-item>
     
        <el-form-item label="商品品牌">
          <el-input
            v-model="form.attributes[0].value"
          ></el-input>
        </el-form-item>
       </div>
        <el-form-item class="beate" label="商品关键字">
          <el-input class="chentea" v-model="form.tags"></el-input>
        </el-form-item>
        <el-form-item>
          <el-col>
            <span class="coenter">规格</span>
             <el-radio-button @click.native="add(index)">
            <el-radio v-model="radio" label="1" values="1">单规格</el-radio>
             </el-radio-button>
            <el-radio v-model="radio" label="2" values="2">多规格</el-radio>
          </el-col>
          <!-- 单规格 -->
          <div v-if="radio === '1'">
            <div v-for="(item, index) in form.specs" :key="index">
              <el-form-item label="商品规格" style="width: 22%" prop="name">
                <el-input class="chenger" v-model="item.name"></el-input>
              </el-form-item>
              <el-form-item
                label="平台售价"
                style="width: 22%"
                prop="costPrice"
              >
                <el-input class="chenger" v-model="item.costPrice"></el-input>
              </el-form-item>
              <el-form-item
                label="市场售价"
                style="width: 22%; margin-left:2%"
                prop="marketPrice"
              >
                <el-input class="chenger" v-model="item.marketPrice"></el-input>
              </el-form-item>
              <el-form-item label="成本价" style="width: 22%" prop="platformPrice">
                <el-input class="chenger" v-model="item.platformPrice"></el-input>
              </el-form-item>
              <el-form-item label="入库数量" style="width: 22%" :prop="'specs.'+ index + '.number'" 
              :rules="[{required:true,message:'入库数量不能为空',trigger:'blur'},{ pattern:/^[1-9]*[1-9][0-9]*$/, message: '入库数量不能小于1', trigger: 'blur' }]">
                <el-input class="chenger" v-model="item.number"></el-input>
              </el-form-item>
            </div>
          </div>
          <!-- 多规格 -->
          <div v-else>
            <div class="aaa" v-for="(item, index) in form.specs" :key="index">
                 <div class="sub-title">商品规格</div>
                <div class="sub-tit">平台售价</div>
                <div class="sub-titl">市场售价</div>
                <div class="sub-titlel">成本价</div>
                <div class="sub-titl">入库数量</div>
                <div class="defchg">
              <el-form-item
                class="defpopt befoemceh"
                style="width: 15%"
              >
                <el-input style="width: 160%" v-model="item.name" ></el-input>
              </el-form-item>
              <el-form-item class="defpopt" style="width: 15%">
                <el-input style="width: 160%" v-model="item.costPrice"></el-input>
              </el-form-item>
              <el-form-item class="defpopt" style="width: 15%">
                <el-input style="width: 160%" v-model="item.marketPrice"></el-input>
              </el-form-item>
              <el-form-item class="defpopt" style="width: 15%">
                <el-input style="width: 160%" v-model="item.platformPrice"></el-input>
              </el-form-item>
              <el-form-item class="defpopt" style="width: 15%"  :prop="'specs.'+ index + '.number'"
              :rules="[{required:true,message:'入库数量不能为空',trigger:'blur'},{ pattern:/^[1-9]*[1-9][0-9]*$/, message: '入库数量不能小于1', trigger: 'blur' }]">
                <el-input style="width: 160%" v-model="item.number"></el-input>
              </el-form-item>
              <el-link :underline="false" @click="submite(index)">删除</el-link>
            </div>
            </div>
            <el-button class="Rectangle" @click="hunem">添加规格</el-button>
          </div>
            <el-form-item label="商品主图">
           <el-upload
             action=""
             :http-request="Upload"
             :data="Aliyun"
             :multiple="false"
             :show-file-list="true"
             list-type="picture-card"
             :file-list="fileList"
             :on-preview="handlePictureCardPreview"
             :on-remove="handleRemove"
             :limit="30"
            >
             <i class="el-icon-plus" />
            </el-upload>
         <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <div class="actuop">建议与提示: 1.图片尺寸建议为1:1大小,单张大小不超过1024kb，仅支持JPG、JPEG、PNG格式。2,图片质量要清晰，不能虚化。</div>
        <!-- 商品详细 -->
         <el-form-item class="actcog" label="商品详细">
           <el-upload
           ref="myUpload"
             action=""
             :http-request="Uploelor"
             :data="Aliyun"
             :multiple="false"
             :show-file-list="true"
             :file-list="imgelor"
             :on-remove="handler"
             :limit="30"
            >
            <el-button class="aote" size="small" type="primary" @click="Uploelor">上传图片</el-button>
            </el-upload>
        </el-form-item>
        <!-- 检测报告 -->
          <el-form-item class="actcog" label="检测报告">
           <el-upload
             action=""
             :http-request="Uplo"
             :data="Aliyun"
             :multiple="false"
             :show-file-list="true"
             :file-list="imgsrc"
             :on-remove="handleRemo"
             :limit="30"
            >
            <el-button size="small" class="affiawd" type="primary" @click="Uplo">上传图片</el-button>
            </el-upload>
        </el-form-item>
          <el-row v-show="this.lifdter != '1'">
            <button class="el-cheron" @click="hSubmit" id="upload">修改商品</button>
          </el-row>
        </el-form-item>
      
      </el-form>
    </el-tabs>
  </div>
</template>

<script>
import { relisdelquery,loginsailuo,information } from "@/api/login";
import { client } from '@/components/Hamburger/ossss'
import {ossmessage,ossuploading} from '@/api/oss'
import {second} from '@/api/user'

// import Indexos from '@/components/Hamburger/index.vue'
// import uploadMixin from '@/mixin/upload';

export default {
  // components:{
  //   Indexos
  // },
  data() {
    return {
      regio:'',
      region: {
            province: "",
            city: "",
            county: ""
           },
      lifdter:'',
      imgs:[],
      imaghe:[],
      imgsrca:[],
      imgelor:[],
      list:[],
      fileList:[],
       dialogImageUrl: '',
       images:[],
      values:'',
      options:[],
      ite: "",
      itek:'',
      dialogVisible:false,
        Aliyun: {}, // 存签名信息
   progress: 0, // 进度条
   imgUrl: [],
    imgsrc:[],
       form: {
      
       commodityId:'',
        title: "",
        mainImages:[],
        categories: [{
           id:'',
           desc:'',
           level:'2'
         }],
        tags: [],
        attributes: [
          {
            name: "checkReportbrand",
            value: ""
          },
           {
            name: "checkReportplace",
            value: ""
          },
             {
            name: "checkReportImages",
            value: ""
          },
              {
            name: "checkReportunit",
            value: ""
          },
            {
            name:"checkReportimg",
            value:''
          }
        ],
        
        specs: [
          {
            commoditySpecId:'',
            commodityId:'',
            name: "",
            platformPrice: "",
            marketPrice: "",
            costPrice: "",
            number: "",
          },
        ],
      },
    level:'',
      radio: '',
      rulesss: {
        title: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.loachengss();
    this.loachehd()
    this.loahovet()
  },
  methods: {
     async loachehd(){
                      // 分类
     const res = await second()
     this.options = res.data  
      
    },
    // 选择分类
  async handleChange(value){
    
       this.form.categories[0].id = value.split('?')[0]
    this.form.categories[0].desc = value.split('?')[1]
   },
   async loachengss() {
     this.form = this.$route.query.row;
     if(this.form.categories.length > 1){

       this.form.categories.splice(0,1)
     }
    
       if(this.form.attributes.length == 4){
           this.form.attributes.push({ name:"checkReportimg",
            value:[]})
       }
       console.log(this.form);
     this.itek = this.form.tags
        this.form['region'] = {
            province: "",
            city: "",
            county: ""
        }
        // console.log(this.form);
 this.lifdter = this.$route.query.a;
      for(let j = 0; j < this.form.specs.length; j++){

        this.form.specs[j].specId = this.form.specs[j].commoditySpecId
    this.form.specs[j].commodityId = this.form.commodityId
      }
    // 数据回填图片
        for(let i = 0; i < this.form.mainImages.length; i++){
           this.fileList.push({
           'url': this.form.mainImages[i],
         })
         }
      // 数据回填检测报告
        this.imgs = JSON.parse(this.form.attributes[2].value)
        // console.log('l112',this.imgs);
      for(let i = 0; i < this.imgs.length; i++){
           this.imgsrc.push({
           'url': this.imgs[i].url,
           'name':this.imgs[i].name
         })
         }
         // 数据回填商品详细
      this.imaghe = JSON.parse(this.form.attributes[4].value)
        // console.log('l112',this.imgs);
      for(let i = 0; i < this.imaghe.length; i++){
           this.imgelor.push({
           'url': this.imaghe[i].url,
           'name':this.imaghe[i].name
         })
         }
    // 单规格多规格
    if(this.form.specs.length > 1){
      this.radio = '2'
    } else{
      this.radio = '1'
    }
        const { data } = await ossmessage({
        'ossGroup':'CommodityMainImages'
      })
    this.Aliyun = data

    },
   async loahovet(){

         const resc = await information()
         this.regio = JSON.parse(resc.data.region)
         this.form.region.province = this.regio.province
         this.form.region.county = this.regio.county
         this.form.region.city = this.regio.city
    },
    // 添加规格
    hunem() {
      let obj = {
        commodityId:'',
        commoditySpecId:'',
        specId:'',
        name: "",
        platformPrice: "",
        marketPrice: "",
        costPrice: "",
        number: "",
      };
   
      // if (this.money <= 5) {
      //   this.money++;
      // }
      if (this.form.specs.length < 30) {
        this.form.specs.push(obj);
      } else{
         this.$message.warning('规格最多添加30个')
      }
    },
     // 单规格
    add(item){
       var index = item;
        this.form.specs.splice(index, this.form.specs.length - 1);
      
      },
    // 删除多规格
    submite(item) {
      var index = item;
      // console.log(index);
      if (this.form.specs.length != 1) {
        this.form.specs.splice(index, 1);
      } else {
        this.$message.warning("最后一个了");
      }
      // if(this.money >= 2){
      // 	this.money--
      // }
    },
        //  商品详细
    Uploelor(file){
       const that = this
    
   // 判断扩展名
   const tmpcnt = file.file.name.lastIndexOf('.')
   const exname = file.file.name.substring(tmpcnt + 1)
   const names = ['jpg', 'jpeg', 'png','webp']
   if (names.indexOf(exname) < 0) {
    this.$message.error('不支持的格式!')
    return
   }
  //  上传文件配置
   async function multipartUpload() {
     const listdata = await ossuploading({
      'fileName':'.jpg','ossGroup':'CommodityMainImages'
    })
     let fileName = listdata.data.path
    //  console.log('741',fileName);
    //  console.log('999',file);
    client(that.Aliyun).put(fileName, file.file,
     {
      progress: function(p) { // 获取进度条的值
      //  console.log('777',p)
       that.progress = p * 100
      }
     }).then(
     result => {
      // 下面是如果对返回结果再进行处理，根据项目需要
      // console.log(result)
      // that.imgUrl = 'http://' + result.bucket + '.' + that.Aliyun.endpoint + '/' + result.name
      that.images.push(result.url)
      that.imgelor.push({
       name: file.file.name,
       url: result.url
      })
      
     })
   }
   multipartUpload()
    },
  // 上传图片检测报告
    Uplo(file){
       const that = this
   // 判断扩展名
   const tmpcnt = file.file.name.lastIndexOf('.')
   const exname = file.file.name.substring(tmpcnt + 1)
   const names = ['jpg', 'jpeg', 'png','webp']
   if (names.indexOf(exname) < 0) {
    this.$message.error('不支持的格式!')
    return
   }
  //  上传文件配置
   async function multipartUpload() {
     const listdata = await ossuploading({
      'fileName':'.jpg','ossGroup':'CommodityMainImages'
    })
     let fileName = listdata.data.path
    //  console.log('741',fileName);
    //  console.log('999',file);
    client(that.Aliyun).put(fileName, file.file,
     {
      progress: function(p) { // 获取进度条的值
      //  console.log('777',p)
       that.progress = p * 100
      }
     }).then(
     result => {
      // 下面是如果对返回结果再进行处理，根据项目需要
      // console.log(result)
      // that.imgUrl = 'http://' + result.bucket + '.' + that.Aliyun.endpoint + '/' + result.name
      // that.images.push(result.url)

      that.imgsrc.push({
       name: file.file.name,
       url: result.url
      })
    
      
     })
   }
   multipartUpload()
    },
   // 上传图片
  Upload(file) {
   const that = this
   // 判断扩展名
   const tmpcnt = file.file.name.lastIndexOf('.')
   const exname = file.file.name.substring(tmpcnt + 1)
   const names = ['jpg', 'jpeg', 'png','webp']
   if (names.indexOf(exname) < 0) {
    this.$message.error('不支持的格式!')
    return
   }
   if (file.size > 1024 * 1024) {
    this.$message.error('图片大小最大1M')
    return
   }
  
   async function multipartUpload() {
    const listdata = await ossuploading({
      'fileName':'.jpg','ossGroup':'CommodityMainImages'
    })
     let fileName = listdata.data.path
    //  console.log('741',fileName);
    //  console.log('999',file);
    client(that.Aliyun).put(fileName, file.file,
     {
      progress: function(p) { // 获取进度条的值
      //  console.log('777',p)
       that.progress = p * 100
      }
     }).then(
     result => {
      
      that.dialogImageUrl = result.url
    
        // console.log('444',that.dialogImageUrl)
      that.imgUrl.push({
       name: file.file.name,
       url: result.url
      })

     that.fileList.push( {'url': that.dialogImageUrl,})
     })
   }
   multipartUpload()
  },
  // 图片预览
  handlePictureCardPreview(file) {
   this.dialogImageUrl = file.url
   this.dialogVisible = true


  },
  // 删除图片
  handleRemove(file, fileList) {
   // console.log(file)
   for (let i in this.fileList) {
     if (this.fileList[i].uid == file.uid) {
     this.fileList.splice(i, 1)
    }
    
   }

  },
    // 删除图片检测报告
  handleRemo(file){
   for (let i in this.imgsrc) {
     if (this.imgsrc[i].uid == file.uid) {
     this.imgsrc.splice(i, 1)
    }
   }
  },
      // 商品详细删除图片
  handler(){
 for (var i in this.imgelor) {
      this.imgelor.splice(i, 1)
   }
  },
    // 提交
  async hSubmit() {
        for(let j = 0; j < this.form.specs.length; j++){
    this.form.specs[j].commodityId = this.form.commodityId
      }
    this.ite = this.form.tags
    if(this.itek != this.ite){

    this.form.tags = this.ite.split(',');
    }

       for(let i = 0; i< this.fileList.length; i++){
          this.list.push(this.fileList[i].url);
     }
      
      this.form.attributes[2].value = JSON.stringify(this.imgsrc)

        this.form.attributes[4].value = JSON.stringify(this.imgelor)
     this.form.mainImages = this.list
      // console.log(this.form.attributes[2].value);
      try {
     
        const res = await loginsailuo(this.form)
      this.$message.success(res.msg)
        this.$router.push('/home/dashboard/commodity')
      } catch(e){
        this.$message.error(e.msg)
      }
      

    },
    // 返回
      hback() {
      this.$router.back();

    },
  },
};
</script>

<style scoped>
.actcone {
  background-color: #fff;
}
.el-form-item {
  display: inline-block;
  flex: 2;
  margin-bottom: 20px;
}
h5 {
  text-align: center;
  font-size: 21px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #e3e5e8;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader {
  display: inline-block;
  margin-left: 30px;
}
.avatar-uploader .el-upload:hover {
  border-color: #ff7144;
}
.avatar-uploader-icon {
  
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px solid rgba(0, 0, 0, 0.2);
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-col {
  margin-right: 10px;
  margin-top: 20px;
  margin-left: 30px;
  display: inline-block;
  height: 50px;
  border-bottom: 1px solid #f9f9f9;
  margin-bottom: 10px;
}
.defpopt {
  margin-right: 10px;
  margin-bottom: 20px;
}

.aaa {
  border-bottom: 1px solid #f9f9f9;
}
.Rectangle {
  width: 111px;
  height: 40px;
  border-radius: 6px 6px 6px 6px;
  opacity: 1;
  border: 1px solid #dcdfe6;
  margin: 15px 0 70px 55px;
}
.el-cheron {
  width: 111px;
  height: 40px;
  background: linear-gradient(90deg, #ff7144 0%, #ff7144 100%);
  border-radius: 6px 6px 6px 6px;
  opacity: 1;
  color: #fff;
  border: 1px solid rgba(0, 0, 0, 0);
  /* transform: translateX(500%); */
  margin-bottom: 50px;
}
.el-row{
  width: 20%;
  margin: 0 auto;
}
.cover-img {
  width: 22vh;
  height: 140px;
  object-fit: cover;
}
.asion {
  transform: translateY(-300%);
}
.coenter {
  display: inline-block;
  margin-right: 20px;
}
.el-link {
  color: #ff7144;
  margin-left: 7%;
}
.el-link:hover {
  color: #ff7144;
}
.actcog{
  display: block;
}
.actcc{
  width: 40%;
  display: block;
  margin-left: 6%;
}
.chentea{
  margin-left: 6%;
}
.aote{
  background: linear-gradient(90deg, #ff7144 0%, #ff7144 100%);
  border: 1px solid #ff7144;
}
::v-deep .el-form-item__label{
  width: 100px !important;
}
::v-deep .el-form-item__content{
  margin-left: 100px !important;
}
.acton{
  width: 100%;
}
.sub-title{
  margin-left: 9%;
  display: inline-block;
}
.sub-tit{
  margin-left: 11%;
  display: inline-block;
}
.sub-titl{
  margin-left: 13%;
  display: inline-block;
}
.sub-titlel{
  margin-left: 12%;
  display: inline-block;
}

.accent{
  margin-left: 6.5%;
}
.chenger{
  width: 93%;
}
.xxloen{
  width: 100%;
}
.beate{
  margin-left: 5%;
}
.defchg{
  margin-left: -3%;
}
.accionceg{
  width: 101%;
}
.vienger{
  display: flex;
  margin-right: 10%;
}
.affiawd{
  border-color: #ff7144;
}
.actuop{
  padding-left: 50px;
  background-color: #FDF9DC;
  width: 1000px;
  color: #C96911;
  margin-left: 32px;
}
</style>